﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;

public class EditorRecordableList<T> where T:new()
{
    private ReorderableList list;
    private List<T> dataList=new List<T>();
    private int focusedIndex = -1;

    public delegate void ElementCallbackDelegate(Rect rect, T data ,int index, bool isActive, bool isFocused);
    public EditorRecordableList(ElementCallbackDelegate drawElement)
    {
        list = new ReorderableList(dataList, typeof(T), true, true, true, true);
        list.drawElementCallback = (rect, index, isActive, isFocused) => {
            if (isFocused)
            {
                focusedIndex = index;
            }
            drawElement(rect, dataList[index], index, isActive, isFocused);
        };
        list.onAddCallback = (reorderList) =>
        {
            dataList.Add(new T());
        };

        list.onRemoveCallback = (reorderList) =>
        {
            dataList.RemoveAt(focusedIndex);
        };
    }

    public void SetData(List<T> dataList)
    {
        this.dataList = dataList;
        list.list = dataList;
    }

    public void SetItemHeight(float height)
    {
        list.elementHeight = height;
    }

    public void Draw()
    {
        list.DoLayoutList();
    }
}